<template>
  <view class="login-container">
    <!-- 应用标题 -->
    <view class="app-header">
      <text class="app-title">密码管理器</text>
      <text class="app-subtitle">安全解锁您的密码库</text>
    </view>

    <!-- 解锁方式选择 -->
    <view class="unlock-methods">
      <view 
        v-for="method in availableMethods" 
        :key="method.key"
        class="method-tab"
        :class="{ active: currentMethod === method.key }"
        @click="switchMethod(method.key)"
      >
        <text class="method-icon">{{ method.icon }}</text>
        <text class="method-text">{{ method.name }}</text>
      </view>
    </view>

    <!-- 密码解锁 -->
    <password-input 
      v-if="currentMethod === 'password'" 
      @submit="handlePasswordSubmit"
      :loading="isLoading"
    />

    <!-- 图案解锁 -->
    <pattern-lock 
      v-if="currentMethod === 'pattern'"
      @complete="handlePatternComplete"
      :loading="isLoading"
    />

    <!-- 指纹解锁 -->
    <view v-if="currentMethod === 'fingerprint'" class="fingerprint-area">
      <view class="fingerprint-icon" :class="{ 'scanning': isScanning }" @click="handleFingerprint">
        <text class="icon">👆</text>
      </view>
      <text class="fingerprint-text">{{ fingerprintText }}</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-spinner"></view>
      <text class="loading-text">验证中...</text>
    </view>

    <!-- 错误提示 -->
    <view v-if="errorMsg" class="error-container">
      <text class="error-icon">⚠️</text>
      <text class="error-msg">{{ errorMsg }}</text>
    </view>

    <!-- 底部提示 -->
    <view class="bottom-tips">
      <text class="tip-text">首次使用请设置主密码</text>
    </view>
  </view>
</template>

<script>
import PatternLock from '@/components/PatternLock.vue'
import PasswordInput from '@/components/PasswordInput.vue'
import { decrypt } from '@/common/crypto.js'
import { checkAuth } from '@/common/api.js'

export default {
  components: { PatternLock, PasswordInput },
  data() {
    return {
      currentMethod: 'password',
      errorMsg: '',
      isLoading: false,
      isScanning: false,
      availableMethods: [
        { key: 'password', name: '密码', icon: '🔐' },
        { key: 'pattern', name: '图案', icon: '🔗' },
        { key: 'fingerprint', name: '指纹', icon: '👆' }
      ],
      deviceCapabilities: {
        fingerprint: false,
        pattern: true,
        password: true
      }
    }
  },
  computed: {
    fingerprintText() {
      if (this.isScanning) return '正在扫描指纹...'
      if (this.isLoading) return '验证中...'
      return '点击进行指纹验证'
    }
  },
  async mounted() {
    await this.checkDeviceCapabilities()
    this.setDefaultMethod()
  },
  methods: {
    // 检查设备能力
    async checkDeviceCapabilities() {
      try {
        // 检查指纹支持
        const res = await uni.checkIsSupportSoterAuthentication({
          requestAuthModes: ['fingerPrint']
        })
        this.deviceCapabilities.fingerprint = res.supportMode.indexOf('fingerPrint') !== -1
        
        // 如果设备不支持指纹，从可用方法中移除
        if (!this.deviceCapabilities.fingerprint) {
          this.availableMethods = this.availableMethods.filter(m => m.key !== 'fingerprint')
        }
      } catch (e) {
        console.log('设备不支持指纹识别')
        this.availableMethods = this.availableMethods.filter(m => m.key !== 'fingerprint')
      }
    },

    // 设置默认解锁方式
    setDefaultMethod() {
      // 优先使用指纹，其次密码，最后图案
      const preferredOrder = ['fingerprint', 'password', 'pattern']
      for (const method of preferredOrder) {
        if (this.availableMethods.find(m => m.key === method)) {
          this.currentMethod = method
          break
        }
      }
    },

    // 切换解锁方式
    switchMethod(method) {
      if (this.isLoading) return // 防止在加载时切换
      this.currentMethod = method
      this.clearError()
    },

    // 清除错误信息
    clearError() {
      this.errorMsg = ''
    },

    // 生成随机challenge
    generateChallenge() {
      return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
    },

    // 处理密码提交
    async handlePasswordSubmit(password) {
      if (this.isLoading) return
      await this.verifyAuth({ type: 'password', value: password })
    },
    
    // 处理图案完成
    async handlePatternComplete(pattern) {
      if (this.isLoading) return
      await this.verifyAuth({ type: 'pattern', value: pattern })
    },
    
    // 指纹验证
    async handleFingerprint() {
      if (this.isLoading || !this.deviceCapabilities.fingerprint) return
      
      this.isScanning = true
      this.clearError()
      
      try {
        const challenge = this.generateChallenge()
        
        const authRes = await uni.startSoterAuthentication({
          requestAuthModes: ['fingerPrint'],
          challenge: challenge,
          authContent: '请验证指纹以解锁应用'
        })
        
        if (authRes.errCode === 0) {
          await this.verifyAuth({ type: 'fingerprint', challenge })
        } else {
          this.handleFingerprintError(authRes.errCode)
        }
      } catch (e) {
        this.errorMsg = '指纹验证失败，请重试'
        console.error('指纹验证错误:', e)
      } finally {
        this.isScanning = false
      }
    },

    // 处理指纹验证错误
    handleFingerprintError(errCode) {
      const errorMessages = {
        90001: '用户取消了指纹验证',
        90002: '指纹验证失败，请重试',
        90003: '指纹验证超时',
        90004: '设备不支持指纹识别',
        90005: '指纹验证被系统中断'
      }
      this.errorMsg = errorMessages[errCode] || '指纹验证失败，请重试'
    },
    
    // 验证授权
    async verifyAuth(authData) {
      if (this.isLoading) return
      
      this.isLoading = true
      this.clearError()
      
      try {
        const token = await checkAuth(authData)
        
        // 保存认证信息
        uni.setStorageSync('authToken', token)
        uni.setStorageSync('lastLoginMethod', this.currentMethod)
        uni.setStorageSync('lastLoginTime', Date.now())
        
        // 显示成功提示
        uni.showToast({
          title: '解锁成功',
          icon: 'success',
          duration: 1500
        })
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          uni.reLaunch({ url: '/pages/index/index' })
        }, 1500)
        
      } catch (e) {
        this.errorMsg = e.message || '验证失败，请重试'
        console.error('验证错误:', e)
        
        // 错误提示自动消失
        setTimeout(() => this.clearError(), 3000)
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60rpx 40rpx;
  box-sizing: border-box;
  position: relative;
}

/* 应用标题 */
.app-header {
  text-align: center;
  margin-bottom: 80rpx;
}

.app-title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: white;
  margin-bottom: 20rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
}

.app-subtitle {
  display: block;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

/* 解锁方式选择 */
.unlock-methods {
  display: flex;
  justify-content: center;
  margin-bottom: 60rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50rpx;
  padding: 10rpx;
  backdrop-filter: blur(10rpx);
}

.method-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 30rpx;
  border-radius: 40rpx;
  transition: all 0.3s ease;
  cursor: pointer;
}

.method-tab.active {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.05);
}

.method-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.method-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

/* 指纹区域 */
.fingerprint-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 100rpx;
}

.fingerprint-icon {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10rpx);
  border: 3rpx solid rgba(255, 255, 255, 0.3);
}

.fingerprint-icon:hover {
  transform: scale(1.1);
  background: rgba(255, 255, 255, 0.3);
}

.fingerprint-icon.scanning {
  animation: pulse 1.5s infinite;
  background: rgba(255, 255, 255, 0.4);
}

.fingerprint-icon .icon {
  font-size: 80rpx;
}

.fingerprint-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  border-top: 6rpx solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

.loading-text {
  color: white;
  font-size: 28rpx;
}

/* 错误提示 */
.error-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40rpx;
  padding: 20rpx 30rpx;
  background: rgba(255, 77, 77, 0.1);
  border-radius: 20rpx;
  border: 2rpx solid rgba(255, 77, 77, 0.3);
  animation: fadeIn 0.3s ease;
}

.error-icon {
  font-size: 32rpx;
  margin-right: 15rpx;
}

.error-msg {
  color: #ff4d4d;
  font-size: 26rpx;
  text-align: center;
}

/* 底部提示 */
.bottom-tips {
  position: absolute;
  bottom: 60rpx;
  left: 0;
  right: 0;
  text-align: center;
}

.tip-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
}

/* 动画 */
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20rpx); }
  to { opacity: 1; transform: translateY(0); }
}
</style>